/*
 * bsp_wdog.c
 *
 *  Created on: 2023年6月28日
 *      Author: mcealt_DS
 */

#include "bsp_wdog.h"
#include "em_cmu.h"
#include "stdbool.h"
#include "softwareMultiTimer.h"
#include "app_log.h"
#include "device_type.h"

#ifdef RFM_DEVICE
#define FEED_WATCH_DOG_TIMEROUT     (12)
#else
#define FEED_WATCH_DOG_TIMEROUT     (3)
#endif

static void initWDOG(void)
{
  // Enable clock for the WDOG module; has no effect on xG21
  CMU_ClockEnable(cmuClock_WDOG0, true);

  // Watchdog Initialize settings
  WDOG_Init_TypeDef wdogInit = WDOG_INIT_DEFAULT;
  CMU_ClockSelectSet(cmuClock_WDOG0, cmuSelect_ULFRCO); /* ULFRCO as clock source */
  wdogInit.em2Run = true;
  wdogInit.em3Run = true;
  #ifdef RFM_DEVICE
  wdogInit.perSel = wdogPeriod_16k; // 2049 clock cycles of a 1kHz clock  ~2 seconds period
  #else
  wdogInit.perSel = wdogPeriod_4k;
  #endif
  // Initializing watchdog with chosen settings
  WDOGn_Init(DEFAULT_WDOG, &wdogInit);
}

void watchDogFeed(void)
{
  WDOGn_Feed(DEFAULT_WDOG);
}


/***********************feed watchdog***************************/

static MultiTimer feedWdogTimer;
static bool feedWdogState = false;

static void feedWdogTimerCallback(MultiTimer* timer, void *userData)
{
  (void)userData;
  (void)timer;
  feedWdogState = true;
}

void feedWatchDogHandler(void)
{
  if(feedWdogState) {
      feedWdogState = false;
      watchDogFeed();
      softwareMultiTimerStart(EN_LP_HARD_TIMER_EM3_SYS_RTC_1, &feedWdogTimer, 32768*FEED_WATCH_DOG_TIMEROUT, feedWdogTimerCallback,NULL,0);
#ifdef SM_KP
      extern void pca9555WriteStateSet(bool state);
      pca9555WriteStateSet(true);
#endif
      DS_app_log_info("feed watch dog \r\n");
  }
}

void startWatchDogTimer(void)
{
  initWDOG();

  softwareMultiTimerStart(EN_LP_HARD_TIMER_EM3_SYS_RTC_1, &feedWdogTimer, 32768*FEED_WATCH_DOG_TIMEROUT, feedWdogTimerCallback,NULL,0);
}
